package com.aiks.dsyncpluginspringbootautoconfigure.plugin;


import com.aiks.dsyncpluginspringbootautoconfigure.enums.ModuleTypeEnum;
import com.aiks.dsyncpluginspringbootautoconfigure.plugin.factory.PluginFactory;
import com.aiks.dsyncpluginspringbootautoconfigure.pojo.ModuleConfigEntity;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * PluginChain.
 *
 * @author <a href="mailto:yuanz@yxt.com">yuanz</a>
 * @date 2022-06-29 10:59
 * @since 1.0.0
 **/
public class PluginChain {
    
    
    private AbstractPlugin abstractPlugin;
    
    private PluginChain() {
    }
    
    public PluginChain(final ModuleTypeEnum moduleTypeEnum) {
        Map<String, Plugin> pluginMap = PluginFactory.INSTANCE.getPluginMap(moduleTypeEnum);
        List<Plugin> plugins = pluginMap.values().stream()
            .sorted(Comparator.comparing(plugin -> plugin.getPluginEnum().getHandleOrder()))
            .collect(Collectors.toList());
        AbstractPlugin next = null;
        for (Plugin plugin : plugins) {
            if (null == abstractPlugin) {
                abstractPlugin = (AbstractPlugin) plugin;
                next = abstractPlugin;
            } else {
                next.setNext((AbstractPlugin) plugin);
                next = next.getNext();
            }
        }
    }
    
    /**
     * execute.
     *
     * @param moduleConfig moduleConfig
     * @param saasDatas    saasDatas
     * @param clientDatas  clientDatas
     * @param <T>          T
     */
    public <T> void execute(final ModuleConfigEntity moduleConfig, final List<T> saasDatas,
                            final List<Object> clientDatas) {
        if (abstractPlugin != null) {
            abstractPlugin.execute(moduleConfig, saasDatas, clientDatas);
        }
    }
    
}
